#!/usr/bin/env python

from sqlite3 import dbapi2 as sqlite
import re

import sys
import time
import urllib2
import hippo
from hippo import OptionParser as OptionParser

QuestionType = 0
AnswerType = 1

def printPhrase(phrase, count, new):
    maxQuestLen = 63
    if len(phrase) > maxQuestLen:
        phrase = phrase[:maxQuestLen-3] + '...'
    if new:
        newIndicator = '(NEW)'
    else:
        newIndicator = ''
    print phrase.ljust(maxQuestLen), "(" +str(count).rjust(3," ") + ")", newIndicator

def processQuestions(cursor, matches, type):
    items = []
    if type == QuestionType:
        print "\nQuestions:"
    else:
        print "\nAnswers:"
    numQuestions = 0
    for question in matches:
        numQuestions += 1
        numVotes = question.group('votes')
        questionId = question.group('questionId')
        questionText = question.group('questionText')
        command = 'SELECT count(id) as count, votes FROM Questions WHERE id = ' + questionId + ' AND type=' + str(type) + ';'

        cursor.execute(command)
        item = cursor.fetchone()
        if item['count'] > 0:
            cursor.execute('UPDATE Questions SET votes = %s WHERE id = %s AND type = %d' % (numVotes, questionId, type))
            newQuestion = (int(numVotes) != item['votes'])
        else:
            cursor.execute('INSERT INTO Questions VALUES("'+questionText+'",'+numVotes+',' + str(type) + ','+questionId+');')
            newQuestion = True

        items.append({'phrase': questionText, 'count': numVotes, 'new': newQuestion})
    return items

def loadProfile(options):
    request = urllib2.Request(url = 'http://stackoverflow.com/users/%i/myProfile.html' % (options.user),
                              headers = { 'Cookie': 'shhsecret=' + options.cookie })
    return urllib2.urlopen(request).read()


def loadOptions(args):
    parser = OptionParser(config_file='overflow.config')
    parser.add_option('-c', '--cookie', help='beta cookie - called "soba" in the page info')
    parser.add_option('-u', '--user', type=int, help='user number')
    (options, args) = parser.parse_args(args)
    return options

    

def main(args=None):
    if args == None:
        args = sys.argv[1:]

    options = loadOptions(args)
    profile = loadProfile(options)
    #print profile

    #oh, and if you use cron, set it once per hour MAX, no need to be unreasonable
    connection = sqlite.connect('profile.db') #profile.db goes in the same directory that os.chdir used earlier
    connection.row_factory = sqlite.Row
    cursor = connection.cursor()
    

    rep = re.search('([\d,]+)</div>.*?<div[^>]*?>Reputation', profile, re.DOTALL).group(1).replace(',', '')
    print rep

    badgeMatches = re.findall('/badges/.*?<br/>', profile)
    badge = 0
    multiplierTarget = 'class="item-multiplier">&times;&nbsp;'
    for b in badgeMatches:
        index = b.find(multiplierTarget)
        if index >= 0:
            countString = b[index + len(multiplierTarget):]
            countString = countString[:countString.find('<')]
            count = int(countString)
        else:
            count = 1
        badge += count

    questionMatches = re.finditer('"vote-count-post"><strong>(?P<votes>\d+)</strong>.*?<h3><a href="/questions/(?P<questionId>\d+)/[^"]+">(?P<questionText>[^>]+)</a>'
                            , profile, re.DOTALL);
    
    answerMatches = re.finditer('<div class="answer-summary"><a href="/questions/(?P<questionId>\d+)[^>]+><div [^>]+>(?P<votes>\d+)</div>.*>(?P<questionText>[^>]+)</a>',
                           profile)

    questions = processQuestions(cursor, questionMatches, QuestionType)
    for question in questions:
        printPhrase(**question)
    numQuestions = len(questions)

    answers = processQuestions(cursor, answerMatches, AnswerType)
    for answer in answers:
        printPhrase(**answer)
    numAnswers = len(answers)

    cursor.execute('SELECT rep, badges, questions, answers , COUNT(date) FROM profile WHERE user = ' + str(options.user) + ' ORDER BY date DESC;')
    oldData = cursor.fetchone()
    if oldData[4] == 0:
        oldData = { 'rep': 0, 'badges': 0, 'questions': 0, 'answers': 0 }
    stTime = time.strftime("%Y-%m-%d %H:%M:%S")
    cursor.execute("INSERT INTO profile VALUES(%s,%s,%s,%s,'%s',%i);" % (rep,badge,numQuestions,numAnswers,stTime, options.user) )
    connection.commit()
    
    print
    print '%s Questions, %s new' % (numQuestions,(numQuestions - oldData['questions']))
    print '%s Answers, %s new' % (numAnswers, numAnswers - oldData['answers'])
    print '%s Reputation (%+i)' % (rep, (int(rep) - oldData['rep']))
    print '%s Badges, %s new' % (badge, (int(badge) - oldData['badges']))


    return 0

#os.system("espeak \"Reputation is at " + rep + " points\"")

##CREATE TABLE "main"."Questions" (
##    "Question" TEXT,
##    "votes" INTEGER,
##    "type" INTEGER,
##    "id" INTEGER
##);

##CREATE TABLE "main"."profile" (
##    "rep" INTEGER,
##    "badges" INTEGER,
##    "questions" INTEGER,
##    "answers" INTEGER,
##    "date" TEXT,
##    "user" INTEGER
##);

if __name__ == '__main__':
    sys.exit(main())

